import java.util.Arrays;

/**
 * @Author: Liu, Yunfeng
 * @DateTime: 2021/8/3 19:42
 * @Description: TODO
 */
public class findUnsortedSubarray {
    public static int findUnsortedSubarray(int[] nums) {
        int[] newNum = nums.clone();
        Arrays.sort(newNum);
        int start = 0;
        int end = nums.length - 1;
        boolean startFlag = false;
        boolean endFlag = false;
        for (int i = 0; i < newNum.length; i++) {
            if (newNum[i] != nums[i]) {
                start = i;
                startFlag = true;
                break;
            }
        }
        for (int i = newNum.length - 1; i >= 0; i--) {
            if (newNum[i] != nums[i]) {
                end = i;
                endFlag = true;
                break;
            }
        }
        if(end <= start || !startFlag || !endFlag){
            return 0;
        }
        return end - start + 1;
    }

    public static void main(String[] args) {
        int[] nums = {1,2,3,4};
        System.out.print(findUnsortedSubarray(nums));
    }
}
